import { useState } from "react";
import { DBContext, StateContext } from "./context";
import { genMessage, MyInfo } from "../../indexdb";

export function AppProvider({
  children,
  db,
}: {
  children: React.ReactNode;
  db: IDBDatabase;
}) {
  const [chatId, _setChatId] = useState("");
  const [msgList, setMsgList] = useState<any[]>([]);
  const setChatId = (id: string) => {
    _setChatId(id);
    queueMicrotask(() => {
      window.deleteByChatIdWithType(id, 18);
      window.readChatAllMsg(id);
    });
  };
  const sendMsg = (ctx: string) => {
    if (!chatId) {
      alert("请先选择聊天");
      return;
    }
    const msg = genMessage();
    msg.content.text = ctx;
    msg.sender = MyInfo.id;
    msg.chatId = chatId;
    msg.aChatId = `a${chatId}`;
    msg.deleteFlag = 0;
    window.putMsgs([msg]).then(async () => {
      const m = await window.getMsgByMid(msg.mid);
      console.log("发送成功", m);
      setMsgList((prev) => [m, ...prev]);
    });
  };
  return (
    <DBContext.Provider value={db}>
      <StateContext.Provider
        value={{ chatId: chatId, setChatId, msgList, setMsgList, sendMsg }}
      >
        {children}
      </StateContext.Provider>
    </DBContext.Provider>
  );
}
